package com.abe.jetpack.view

import android.arch.lifecycle.Observer
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.abe.jetpack.R
import com.abe.jetpack.base.AutoBaseActivity
import com.abe.jetpack.model.entity.http.AuthorEntity
import com.abe.jetpack.viewmodel.WanAndroidModel
import com.abe.libcore.utils.CommonUtils
import com.abe.libcore.view.recyclerview.CommonAdapter
import com.abe.libcore.view.recyclerview.MultiItemTypeAdapter
import com.abe.libcore.view.recyclerview.base.ViewHolder
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration
import kotlinx.android.synthetic.main.activity_wx_main.*

class WxArticleActivity : AutoBaseActivity() {
    override fun initContent() {
        initRV()
        httpTest()
    }

    private val wanAndroid by lazy { getInjectViewModel<WanAndroidModel>() }
    private lateinit var authorEntities: ArrayList<AuthorEntity>
    private lateinit var adapter: CommonAdapter<AuthorEntity>

    private fun initRV() {
        authorEntities = arrayListOf()
        adapter = object : CommonAdapter<AuthorEntity>(getContext(), R.layout.item_wx_author, authorEntities) {
            override fun isAutoZoom(): Boolean {
                return true
            }

            override fun convert(holder: ViewHolder?, t: AuthorEntity?, position: Int) {
                holder!!.setText(R.id.item_rv_name, t!!.name)
            }
        }
        adapter.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener {
            override fun onItemClick(view: View?, holder: RecyclerView.ViewHolder?, position: Int) {
                CommonUtils.log(authorEntities[position].name)
            }

            override fun onItemLongClick(view: View?, holder: RecyclerView.ViewHolder?, position: Int): Boolean {
                return false
            }
        })
        item_main_rv.layoutManager = LinearLayoutManager(getContext())
        item_main_rv.addItemDecoration(DefaultItemDecoration(Color.TRANSPARENT))
        item_main_rv.adapter = adapter
    }

    private fun httpTest() {
        wanAndroid.getAuthors(lifecycle)
                .observe(this, Observer<List<AuthorEntity>> { t ->
                    runOnUiThread {
                        authorEntities.clear()
                        authorEntities.addAll(t!!)
                        adapter.notifyDataSetChanged()
                    }
                })
    }

    override fun getLayoutRes(): Int {
        return R.layout.activity_wx_main
    }
}